package com.hd.service.personaloffice.impl;

import com.hd.dao.BaseDao;
import com.hd.entity.*;
import com.hd.entity.enums.*;
import com.hd.entity.personaloffice.WorkCommentOpinion;
import com.hd.entity.personaloffice.WorkSummary;
import com.hd.entity.sys.User;
import com.hd.service.*;
import com.hd.service.job.QuartzScheduleJobService;
import com.hd.service.personaloffice.WorkCommentOpinionService;
import com.hd.service.personaloffice.WorkSummaryService;
import com.hd.service.sys.UserService;
import com.hd.util.StringUtils;
import com.hd.util.result.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: hzhh123
 * @Date: 2018/12/24 23:03
 * 工作日报|周报|季度报|年度总结
 */
@Service("workSummaryService")
public class WorkSummaryServiceImpl implements WorkSummaryService {
    @Autowired
    private BaseDao<WorkSummary,String>workSummaryDao;

    @Autowired
    private WorkCommentOpinionService workCommentOpinionService;
    @Autowired
    private AttachService attachService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuartzScheduleJobService quartzScheduleJobService;
    @Autowired
    private TodoService todoService;
    @Autowired
    private WorkCcService workCcService;
    @Override
    public Serializable save(WorkSummary workSummary) {
        Date now=new Date();
        workSummary.setId(UUID.randomUUID().toString());
        workSummary.setOperateTime(now);
        workSummary.setSaveDate(now);
        String id=(String)workSummaryDao.save(workSummary);
        saveWorkCommentOpinion(workSummary);
        return id;
    }

    /**
     * 保存待评论和抄送信息
     * @param workSummary
     */
    private void saveWorkCommentOpinion(WorkSummary workSummary){
        String msgIds="";
        String commentOpinionIds="";
        /**
         * 主送
         */
        if(StringUtils.isNotNull(workSummary.getCommentators())){
            String str[] = workSummary.getCommentators().split(",");
            for (String s : str) {
                saveObj1(workSummary,s);
            }
        }

        /**
         * 抄送
         */
        if(StringUtils.isNotNull(workSummary.getUseridCcs())){
            String str[] = workSummary.getUseridCcs().split(",");
            for (String s : str) {
                saveObj2(workSummary,s);
            }
        }
    }

    /**
     * 保存计划评论|消息|待办
     * @param workSummary
     * @param s
     */
    private void saveObj1(WorkSummary workSummary,String s){
        Msg msg=new Msg();
        msg.setType(MsgEnum.WORK_SUMMARY.getName());
        msg.setReceiver(s);
        msg.setContent(workSummary.getName()+"【待审批】");
        msg.setStatus(MsgStatusEnum.ON.getStatus());
        msg.setObjId(workSummary.getId());
        msgService.save(msg);
        /***********************保存待办******************/
        Todo todo=new Todo();
        todo.setCreateTime(new Date());
        todo.setObjId(workSummary.getId());
        todo.setStatus(TodoStatusEnum.TODO.getStatus());
        todo.setTitle(workSummary.getName());
        todo.setType(TodoTypeEnum.WORK_SUMMARY.getType());
        todo.setTypeName(TodoTypeEnum.WORK_SUMMARY.getMsg());
        todo.setUserId(s);
        todo.setOperatorURL(TodoTypeEnum.WORK_SUMMARY.getUrl()+workSummary.getId());
        todoService.save(todo);
        /***************************************************/
        WorkCommentOpinion opinion = new WorkCommentOpinion();
        opinion.setCommentator(s);
        opinion.setObjId(workSummary.getId());
        opinion.setType(WorkCommentOpinion.WORK_SUMMARY);
        workCommentOpinionService.save(opinion);
    }

    public void saveObj2(WorkSummary workSummary,String s){
        Msg msg=new Msg();
        msg.setType(MsgEnum.WORK_SUMMARY.getName());
        msg.setReceiver(s);
        msg.setObjId(workSummary.getId());
        msg.setContent(workSummary.getName()+"【抄送】");
        msg.setStatus(MsgStatusEnum.ON.getStatus());
        msgService.save(msg);
        //保存抄送
        WorkCc workCc=new WorkCc();
        workCc.setObjId(workSummary.getId());
        workCc.setTitle(workSummary.getName());
        workCc.setType(WorkCcTypeEnum.WORK_SUMMARY.getType());
        workCc.setTypeName(WorkCcTypeEnum.WORK_SUMMARY.getMsg());
        workCc.setUserId(s);
        workCc.setOperatorURL(WorkCcTypeEnum.WORK_SUMMARY.getPrefixUrl()+workSummary.getId());
        workCcService.save(workCc);

    }

    private void deleteObj1(String id,String userid){
        if(userid!=null) {
            //1)删除评论
            workCommentOpinionService.deleteByParams(id, userid, WorkCommentOpinion.WORK_SUMMARY);
            //2)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_SUMMARY.getName(), userid);
            //3)删除待办
            todoService.deleteByParams(id, TodoTypeEnum.WORK_SUMMARY.getType(), userid);
        }else {
            //1)删除评论
            workCommentOpinionService.deleteByParams(id, WorkCommentOpinion.WORK_SUMMARY);
            //2)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_SUMMARY.getName());
            //3)删除待办
            todoService.deleteByParams(id, TodoTypeEnum.WORK_SUMMARY.getType());
        }
    }
    private void deleteObj2(String id,String userid){
        if (userid!=null) {
            //1)删除消息
            msgService.deleteByParams(id, MsgEnum.WORK_SUMMARY.getName(), userid);
            //2)删除抄送
            workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_SUMMARY.getType(),userid);
        }else {
            msgService.deleteByParams(id, MsgEnum.WORK_SUMMARY.getName());
            workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_SUMMARY.getType());
        }
    }

    @Override
    public void update(WorkSummary workSummary) {
        WorkSummary vo=workSummaryDao.get(WorkSummary.class,workSummary.getId());
        workSummary.setSaveDate(vo.getSaveDate());
        workSummary.setOperateTime(new Date());
        workSummary.setStatus(vo.getStatus());
        workSummary.setLastUpdateTime(new Date());
        String oldCommentators=vo.getCommentators();
        String oldUseridCcs=vo.getUseridCcs();
        workSummaryDao.update(workSummary);
        saveNewCommentators(workSummary,oldCommentators);
        saveNewUseridCcs(workSummary,oldUseridCcs);

    }

    /**
     * 保存新增-删除审批人
     * @param workSummary
     * @param oldCommentators
     */
    private void saveNewCommentators(WorkSummary workSummary,String oldCommentators){
        String newCommentators=workSummary.getCommentators();
        if(StringUtils.isNotNull(newCommentators)){
            String s1[]=newCommentators.split(",");
            Set<String>set1=new HashSet<>();
            Set<String>set2=new HashSet<>();
            Set<String>set3=new HashSet<>();
            Set<String>result=new HashSet<>();
            for(String s:s1){
                set1.add(s);
                set2.add(s);
            }
            if (StringUtils.isNotNull(oldCommentators)) {
                //不为空，相同的不处理，不同需要增加或删除
                String s2[]=oldCommentators.split(",");
                for(String s:s2){
                    set3.add(s);
                }
                //set1与set3交集
                set1.retainAll(set3);
                result.clear();
                result.addAll(set2);
                result.removeAll(set1);
                //此时得到的是新增的部分
                if(result.size()>0){
                    for (String s:result){
                        saveObj1(workSummary,s);
                    }
                }
                result.clear();
                result.addAll(set3);
                result.removeAll(set1);
                if(result.size()>0){
                    //删除
                    for (String s:result){
                        deleteObj1(workSummary.getId(),s);
                    }
                }

            }else{
                //审批人为空，则直接插入
                for(String s:s1){
                    saveObj1(workSummary,s);
                }
            }
        }else{
            deleteObj1(workSummary.getId(),null);
        }
    } /**
     * 保存新增-删除抄送人
     * @param workSummary
     * @param oldUseridCcs
     */
    private void saveNewUseridCcs(WorkSummary workSummary,String oldUseridCcs){
        String newUseridCcs=workSummary.getUseridCcs();
        if(StringUtils.isNotNull(newUseridCcs)){
            String s1[]=newUseridCcs.split(",");
            Set<String>set1=new HashSet<>();
            Set<String>set2=new HashSet<>();
            Set<String>set3=new HashSet<>();
            Set<String>result=new HashSet<>();
            for(String s:s1){
                set1.add(s);
                set2.add(s);
            }
            if (StringUtils.isNotNull(oldUseridCcs)) {
                //不为空，相同的不处理，不同需要增加或删除
                String s2[]=oldUseridCcs.split(",");
                for(String s:s2){
                    set3.add(s);
                }
                //set1与set3交集
                set1.retainAll(set3);
                result.clear();
                result.addAll(set2);
                result.removeAll(set1);
                //此时得到的是新增的部分
                if(result.size()>0){
                    for (String s:result){
                        saveObj2(workSummary,s);
                    }
                }
                result.clear();
                result.addAll(set3);
                result.removeAll(set1);
                if(result.size()>0){
                    //删除
                    for (String s:result){
                        deleteObj2(workSummary.getId(),s);
                    }
                }

            }else{
                //审批人为空，则直接插入
                for(String s:s1){
                    saveObj2(workSummary,s);
                }
            }
        }else{
            deleteObj2(workSummary.getId(),null);
        }
    }


    @Override
    public WorkSummary get(String id) {
        WorkSummary workSummary=workSummaryDao.get(WorkSummary.class,id);
        convert(workSummary);
        return workSummary;
    }

    /**
     * 封装其他参数
     * @param workSummary
     */
    private void convert(WorkSummary workSummary){
        if(StringUtils.isNotNull(workSummary.getUserid())){
            //查询用户
            User user=userService.get(workSummary.getUserid());
            if(user!=null){
                workSummary.setUserName(user.getName());
            }
        }
        //附件
        if(StringUtils.isNotNull(workSummary.getAttachIds())){
            List<Attach>attachList=attachService.findInIds(workSummary.getAttachIds());
            workSummary.setAttachList(attachList);
        }
        //评论
        if(StringUtils.isNotNull(workSummary.getCommentators())){
            List<WorkCommentOpinion>opinions=workCommentOpinionService.findByParams(workSummary.getId(),WorkCommentOpinion.WORK_SUMMARY);
            workSummary.setWorkCommentOpinionList(opinions);
            String commentatorNames="";
            if(opinions.size()>0) {
                for (WorkCommentOpinion opinion : opinions) {
                    commentatorNames += opinion.getCommentatorName() + ",";
                }
                commentatorNames = commentatorNames.substring(0, commentatorNames.lastIndexOf(","));
                workSummary.setCommentatorNames(commentatorNames);
            }
        }
        //抄送人
        if(StringUtils.isNotNull(workSummary.getUseridCcs())){
            List<User> users=userService.getUserByIds(workSummary.getUseridCcs());
            if(users.size()>0){
                String userNameCcs="";
                for(User user:users){
                    userNameCcs+=user.getName()+",";
                }
                userNameCcs=userNameCcs.substring(0,userNameCcs.lastIndexOf(","));
                workSummary.setUserNameCcs(userNameCcs);
            }
        }
    }
    @Override
    public void delete(String id) {
        //1)删除计划
        workSummaryDao.delete(WorkSummary.class, id);
        //2)删除评论
        workCommentOpinionService.deleteByParams(id,WorkCommentOpinion.WORK_SUMMARY);
        //3)删除消息
        msgService.deleteByParams(id,MsgEnum.WORK_SUMMARY.getName());
        //4)删除待办
        todoService.deleteByParams(id,TodoTypeEnum.WORK_SUMMARY.getType());
        //5)删除抄送
        workCcService.deleteByParams(id,WorkCcTypeEnum.WORK_SUMMARY.getType());
    }

    @Override
    public void selectDataGrid(PageInfo info, WorkSummary workSummary) {
        Integer page=info.getNowpage();
        Integer pageSize=info.getPagesize();
        Map<String,Object> condition=info.getCondition();
        List<Object>params=new ArrayList<>();
        String hql="from WorkSummary where 1=1";
        if(StringUtils.isNotNull(workSummary.getUserid())){
            hql+=" and userid>=?";
            params.add(workSummary.getUserid());
        }
        if(StringUtils.isNotNull(workSummary.getSaveDateStart())){
            hql+=" and saveDate>=?";
            params.add(workSummary.getSaveDateStart());
        }

        if(StringUtils.isNotNull(workSummary.getSaveDateEnd())){
            hql+=" and saveDate<=?";
            params.add(workSummary.getSaveDateEnd());
        }
        if(StringUtils.isNotNull(workSummary.getName())){
            hql+=" and name like ?";
            params.add("%"+workSummary.getName()+"%");
        }

        if(StringUtils.isNotNull(workSummary.getType())){
            hql+=" and type=?";
            params.add(workSummary.getType());
        }
        if(StringUtils.isNotNull(workSummary.getStatus())){
            hql+=" and status=? ";
            params.add(workSummary.getStatus());
        }else{
            hql+=" and status=? ";
            params.add(1);
        }

        hql+=" order by saveDate desc";
        String countSql="select count(*) "+hql;
        List<WorkSummary>workSummarys=workSummaryDao.findPage(hql,page,pageSize,params);
        if(workSummarys.size()>0){
            for (WorkSummary workSummary1:workSummarys){
                convert(workSummary1);
            }
        }
        info.setRows(workSummarys);
        int total=Integer.parseInt(workSummaryDao.getCountByList(countSql,params)+"");
        info.setTotal(total);

    }

    @Override
    public List<WorkSummary> getBySaveDate(Date saveDate,String userid) {
        String hql="from WorkSummary where saveDate=? and status=1 and userid=?";
        List<WorkSummary>workSummarys=new ArrayList<>();
        workSummarys=workSummaryDao.find(hql,saveDate,userid);
        if(workSummarys.size()>0){
            for(WorkSummary workSummary:workSummarys){
                convert(workSummary);
            }
        }
        return workSummarys;
    }


    /**
     * 修改工作计划状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        String hql="update WorkSummary set status=?,lastUpdateTime=? where id=?";
        workSummaryDao.execute(hql,status,new Date(),id);
        if(status==-1){
            //作废
            todoService.update(id,TodoStatusEnum.CANCEL.getStatus(),TodoTypeEnum.WORK_SUMMARY.getType());
            msgService.update(id,MsgStatusEnum.CANCEL.getStatus(),MsgEnum.WORK_SUMMARY.getName());
        }
    }
    /**
     * 通过月份查询
     * @param date  格式YYYY-MM
     * @return
     */
    @Override
    public List<WorkSummary> getByMonth(String date,String userid)throws Exception {
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String date1=date+"-01";
        String date2=date+"-31";
        Date d1=df.parse(date1);
        Date d2=df.parse(date2);
        String hql="from WorkSummary where saveDate>=? and saveDate<=? and userid=? and status=1";
        List<WorkSummary>workSummarys=new ArrayList<>();
        workSummarys=workSummaryDao.find(hql,d1,d2,userid);
        if(workSummarys.size()>0){
            for(WorkSummary workSummary:workSummarys){
                convert(workSummary);
            }
        }
        return workSummarys;
    }
}

